<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form :inline="true" ref="searchForm" :model="searchObj" :rules="searchRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请输入" v-model.trim="searchObj.roleName" @keyup.enter.native="doSearch()">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSearch">搜索</el-button>
          <el-button type="primary" @click="doReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row class="mt-20 pl-10" type="flex" justify="start" :gutter="20">
      <el-button type="success" @click="showDialog('新增')">新增</el-button>
    </el-row>
    <el-table class="mt-20" :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="roleName" label="角色名称">
      </el-table-column>
      <el-table-column prop="roleDesc" label="角色描述">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="showDialog('编辑',scope.row.roleId)">编辑</el-button>
          <el-button type="text" size="small" @click="showComfirm(scope.row.roleId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="mt-20" type="flex" justify="center">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-row>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="dialogClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="form.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model.trim="form.roleDesc"></el-input>
        </el-form-item>
        <el-form-item label="选择权限">
          <el-button @click="showTreeDialog">选择</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="addOrEdit">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="角色权限" :visible.sync="treeDialogVisible" :fullscreen="true" :before-close="treeDialogClose" width="96%">
      <el-row>
        <el-col v-if="false" :span="6">
          <h3>社交系统</h3>
          <el-tree
            ref="crmTree"
            show-checkbox
            :data="crmList"
            :props="treeProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            @check-change="getCrmKeys">
          </el-tree>
        </el-col>
        <el-col :span="6">
          <h3>物管系统</h3>
          <el-tree
            ref="estateTree"
            show-checkbox
            :data="estateList"
            :props="treeProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"

            @check-change="getEstateKeys">
          </el-tree>
        </el-col>
        <el-col :span="6">
          <h3>OA系统</h3>
          <el-tree
            ref="oaTree"
            show-checkbox
            :data="oaList"
            :props="treeProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            @check-change="getOaKeys">
          </el-tree>
        </el-col>
        <el-col :span="6">
          <h3>物业人员App</h3>
          <el-tree
            ref="assistantTree"
            show-checkbox
            :data="assistantList"
            :props="treeProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            @check-change="getAssistantKeys">
          </el-tree>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="treeDialogClose">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { findAllRole,addRole,updateRole,deleteRole,findPrivileges,findRole } from "@/api/departPersonManage/roleManagement";
import { roleManagementTableData,departManagementTreeData } from "@/constants/mockDatas";
import { deleteConfirm } from "@/utils/deleteConfirm";
import { requireInput,requireInputWithMaxLengthN } from "@/utils/validateForm";
import { systemList} from "@/constants/code";
const totree = require('totree');

export default {
  data() {
    const validateDate = (rule, value, callback) => {
      let num =
        new Date(this.searchObj.startTime).getTime() -
        new Date(this.searchObj.endTime).getTime();
      if (num > 0) {
        callback(new Error("结束时间不能超过开始时间"));
      } else if (value == "") {
        callback(new Error("请选择结束时间"));
      } else {
        callback();
      }
    };

    return {
      searchObj: {
        roleName:''
      },
      searchRules: {
        roleName: requireInputWithMaxLengthN()
      },
      list: [],
      listLoading: false,
      currentPage: 1,
      total: 0,
      pageSize: 5,
      pageSizes: [5, 10],
      btnDisabled: true,
      multipleSelection: [],
      dialogCount: 0,
      dialogVisible: false,
      detailDialogVisible:false,
      dialogTitle: "添加版本",
      detailDialogTitle:"详情",
      form: {
        roleName: '',
        roleDesc: '',
      },
      rules: {
        roleName:[...requireInput("请输入角色名称"),...requireInputWithMaxLengthN()],
      },
      systemList,
      fileList3:[],
      systemId: 1,
      treeDialogVisible: false,
      treeProps: {
        label: 'privilegeName'
      },
      crmList: [],
      estateList: [],
      oaList: [],
      assistantList: [],
      crmKeys: [],
      estateKeys: [],
      oaKeys: [],
      assistantKeys: [],
      privilegeIds: [],
      roleId: null,
      crmData: [],
      estateData: [],
      oaData: [],
      assistantData: []
    };
  },
  created() {
    this.findAllRoleAsync();
    this.findPrivilegesAsync();
  },
  methods: {
    doSearch() {
      this.$refs.searchForm.validate(vaild=> {
        if(vaild) {
          this.findAllRoleAsync();
        }
      })
    },

    doReset() {
      this.$refs.searchForm.resetFields(); //对整个表单进行重置
      this.findAllRoleAsync();
    },

    showDialog(type, roleId) {
      this.dialogTitle = type;
      if (roleId) {
        this.findRoleAsync(roleId)
      }else{
        if(this.$refs.estateTree) {
          let treeNames = ['estateTree','oaTree','assistantTree'];


          for(let i of treeNames) {
            this.$refs[i].setCheckedKeys([]);
          }
        }



        this.privilegeIds = [];
        this.form = {
          roleName: '',
          roleDesc: '',
        }
      }
      this.dialogVisible = true;
    },

    showDetailDialog(scope){
      this.detailForm = scope
      this.detailDialogVisible = true
    },

    showTreeDialog() {

      this.treeDialogVisible = true;

      setTimeout(()=> {
        if(this.dialogTitle=='编辑') {
          let trees = [
            {
              treeName: 'estateTree',
              treeData: 'estateData',
            },
            {
              treeName: 'oaTree',
              treeData: 'oaData',
            },
            {
              treeName: 'assistantTree',
              treeData: 'assistantData',
            },
          ];


          trees.forEach((tree)=> {
            let keys = this[tree.treeData].map(tree=> tree.privilegeId);
            let exclude = (a,b) => {
              let set = new Set(b)
              return a.filter(item => set.has(item))
            }
            let ids = exclude(this.privilegeIds,keys)
            this.$refs[tree.treeName].setCheckedKeys(ids);
          })
        }
      },300)


    },

    addOrEdit() {
      if(this.form.roleName=='admin') {
        this.$message({
          type: 'error',
          message: '角色名称不能为admin'
        });
        return;
      }
      this.$refs.form.validate((vaild)=>{
        if(vaild) {
          if (this.dialogTitle == "新增") {
            this.addRoleAsync()
          } else {
            this.updateRoleAsync()
          }


        }
      })
    },

    dialogClose() {
      this.$refs.form.resetFields();

      this.dialogVisible = false;
      this.form = {
        roleName: '',
        roleDesc: '',
      };

    },

    handleDetailClose(){
      this.detailDialogVisible = false
    },

    doDelete() {
      this.deleteRoleAsync(this.roleId);
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.findAllRoleAsync();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.findAllRoleAsync();
    },

    showComfirm(id = null) {
      this.roleId = id;
      deleteConfirm(this, this.doDelete, this.findAllRoleAsync);
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.btnDisabled = this.multipleSelection.length < 1;
    },
    handleChange(file, fileList) {
        this.fileList3 = fileList.slice(-3);
    },


    treeDialogClose() {
      if(this.dialogTitle=='新增') {
        if(this.$refs.estateTree) {
          let treeNames = ['estateTree','oaTree','assistantTree'];


          for(let i of treeNames) {
            this.$refs[i].setCheckedKeys([]);
          }
        }
      }
      this.treeDialogVisible = false;
    },

    sure() {
      this.privilegeIds = [...this.crmKeys,...this.estateKeys,...this.oaKeys,...this.assistantKeys];
      if(this.privilegeIds.length==0) {
        this.$message({
          type: 'warning',
          message: '未选择任何权限！'
        })
        return;
      }
      this.treeDialogVisible = false;
    },

    getCrmKeys() {
      this.crmKeys = this.$refs.crmTree.getCheckedKeys()
    },

    getEstateKeys() {
      this.estateKeys = this.$refs.estateTree.getCheckedKeys()
    },

    getOaKeys() {
      this.oaKeys = this.$refs.oaTree.getCheckedKeys()
    },

    getAssistantKeys() {
      this.assistantKeys = this.$refs.assistantTree.getCheckedKeys()
    },

    async findAllRoleAsync() {
      let {code,data,msg} = await findAllRole({
        ...this.searchObj,

      },{
        page: this.currentPage,
        pageSize: this.pageSize
      })
      if(code=='00000') {
        this.list = data.rows;
        this.total = data.total;
      }
    },

    async addRoleAsync() {
      let privilegeIds = this.privilegeIds.join(',');
      let {code,data,msg} = await addRole({
        ...this.form,
        privilegeIds
      });
      if(code=='00000') {
        this.findAllRoleAsync();
        this.dialogVisible = false;
      }
    },

    async updateRoleAsync() {
      let privilegeIds = this.privilegeIds.join(',');
      let {code,data,msg} = await updateRole({
        ...this.form,
        privilegeIds
      });
      if(code=='00000') {
        this.findAllRoleAsync();
        this.dialogVisible = false;
      }
    },

    async deleteRoleAsync(ids) {
      let {code,data,msg} = await deleteRole({
        roleId: ids
      });
      if(code=='00000') {
        this.findAllRoleAsync();
      }
    },

    async findPrivilegesAsync() {
      let {code,data,msg} = await findPrivileges();

      if(code=='00000') {

        let crmList = data.estateList.map(item=> {
          return {
            ...item,
            id: item.privilegeId,
            pid: item.parentId
          }
        });

        let estateList = data.estateList.map(item=> {
          return {
            ...item,
            id: item.privilegeId,
            pid: item.parentId
          }
        });

        let oaList = data.oaList.map(item=> {
          return {
            ...item,
            id: item.privilegeId,
            pid: item.parentId
          }
        });

        let assistantList = data.assistantList.map(item=> {
          return {
            ...item,
            id: item.privilegeId,
            pid: item.parentId
          }
        });


        this.crmList = totree(crmList);
        this.estateList = totree(estateList);
        this.oaList = totree(oaList);
        this.assistantList = totree(assistantList);

        this.crmData = crmList;
        this.estateData = estateList;
        this.oaData = oaList;
        this.assistantData = assistantList;

      }
    },

    async findRoleAsync(roleId) {
      let {code,data,msg} = await findRole({
        roleId
      });
      if(code=='00000') {
        this.form.roleName = data.roleName;
        this.form.roleDesc = data.roleDesc;
        this.privilegeIds = data.privilegeIds.split(',');
        this.form.roleId = data.roleId;







      }
    }


  }
};
</script>
